package com.todo.controller;

import com.todo.common.Result;
import com.todo.service.AiService;
import com.todo.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * AI总结控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/ai")
@CrossOrigin(origins = "*")
public class AiController {

    @Autowired
    private AiService aiService;

    @Autowired
    private JwtUtil jwtUtil;

    @GetMapping("/index")
    public Result<Map<String, Object>> index(HttpServletRequest request) {
        return Result.success();
    }

    /**
     * 生成当日待办总结
     */
    @PostMapping("/summary/daily")
    public Result<Map<String, Object>> generateDailySummary(HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            String summary = aiService.generateDailySummary(userId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("type", "daily");
            result.put("date", LocalDate.now().toString());
            result.put("summary", summary);
            result.put("generatedAt", System.currentTimeMillis());
            
            return Result.success("生成成功", result);
        } catch (Exception e) {
            log.error("生成当日总结失败", e);
            return Result.error("生成总结失败：" + e.getMessage());
        }
    }

    /**
     * 生成本周待办总结
     */
    @PostMapping("/summary/weekly")
    public Result<Map<String, Object>> generateWeeklySummary(HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            String summary = aiService.generateWeeklySummary(userId);
            
            LocalDate today = LocalDate.now();
            LocalDate startOfWeek = today.minusDays(today.getDayOfWeek().getValue() - 1);
            LocalDate endOfWeek = startOfWeek.plusDays(6);
            
            Map<String, Object> result = new HashMap<>();
            result.put("type", "weekly");
            result.put("startDate", startOfWeek.toString());
            result.put("endDate", endOfWeek.toString());
            result.put("summary", summary);
            result.put("generatedAt", System.currentTimeMillis());
            
            return Result.success("生成成功", result);
        } catch (Exception e) {
            log.error("生成本周总结失败", e);
            return Result.error("生成总结失败：" + e.getMessage());
        }
    }

    /**
     * 生成自定义日期范围的待办总结
     */
    @PostMapping("/summary/custom")
    public Result<Map<String, Object>> generateCustomSummary(
            @RequestParam String startDate,
            @RequestParam String endDate,
            HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            LocalDate start = LocalDate.parse(startDate);
            LocalDate end = LocalDate.parse(endDate);
            
            if (start.isAfter(end)) {
                return Result.error("开始日期不能晚于结束日期");
            }
            
            String summary = aiService.generateSummary(userId, start, end);
            
            Map<String, Object> result = new HashMap<>();
            result.put("type", "custom");
            result.put("startDate", startDate);
            result.put("endDate", endDate);
            result.put("summary", summary);
            result.put("generatedAt", System.currentTimeMillis());
            
            return Result.success("生成成功", result);
        } catch (Exception e) {
            log.error("生成自定义总结失败", e);
            return Result.error("生成总结失败：" + e.getMessage());
        }
    }

    /**
     * 测试AI连接
     */
    @PostMapping("/test")
    public Result<String> testAiConnection(@RequestParam(required = false, defaultValue = "openai") String provider) {
        try {
            String testPrompt = "请简单回复'连接成功'来测试API连接。";
            String response = aiService.callAiModel(testPrompt, provider);
            return Result.success("AI连接测试成功", response);
        } catch (Exception e) {
            log.error("AI连接测试失败", e);
            return Result.error("AI连接测试失败：" + e.getMessage());
        }
    }

    /**
     * 从请求中获取用户ID
     */
    private Long getUserIdFromRequest(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            return jwtUtil.getUserIdFromToken(token);
        }
        throw new RuntimeException("未授权访问");
    }
} 